#!/bin/sh
#
# Copyright (C) 2000-2022 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Attempt to backup and restore a file with the bpipe plugin
#
TestName="sdplugin-test"
JobName=pluginTest
. scripts/functions

scripts/cleanup
scripts/copy-plugin-confs
make -C $src/src/plugins/fd install-test-plugin

file=encrypt-bug.jpg
rm -rf ${cwd}/tmp/*
echo "${cwd}/README" >${cwd}/tmp/file-list

start_test

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@output /dev/null
messages
@$out ${cwd}/tmp/log1.out
setdebug level=150 storage=File1
label storage=File1 volume=TestVolume001
run job=$JobName storage=File1 yes
wait
status storage=File1
messages
run job=TestPluginTest storage=File1 yes
wait
status storage=File1
messages
quit
END_OF_DATA


run_bacula

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
messages
@# 
@# now do a restore
@#
@$out ${cwd}/tmp/log2.out
restore fileset=pluginSet where=${cwd}/tmp  select all storage=File1 done
yes
wait
messages
quit
END_OF_DATA

run_bconsole

stop_bacula

# ****FIXME**** test if the restore of the two files is OK

#
# Remove plugin so we can try the restore without the plugin
#
mv -f ${cwd}/bin/plugins/bpipe-fd.so ${cwd}/bin/plugins/bpipe-fd.sox

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@$out ${cwd}/tmp/log2.out
@# remove plugin
@exec "sh -c 'rm -f ${cwd}/bin/plugins/bpipe-fd.so'"
@# 
@# now do a restore without the plugin
@#
@$out ${cwd}/tmp/log2.out
@#setdebug level=50 client=$CLIENT
restore fileset=pluginSet where=${cwd}/tmp  select all storage=File1 done
yes
wait
messages
quit
END_OF_DATA

run_bacula -d50
run_bconsole

cat <<END_OF_DATA >${cwd}/tmp/bconcmds
messages
@# 
@# now do a restore
@#
@$out ${cwd}/tmp/log3.out
setdebug level=50 client=$CLIENT trace=1
restore fileset=TestPluginSet where=${cwd}/tmp  select all storage=File1 done
yes
wait
setdebug level=0 client=$CLIENT trace=0
messages
quit
END_OF_DATA

run_bconsole

check_for_zombie_jobs storage=File1
stop_bacula
#
# Restore plugin
#
mv -f ${cwd}/bin/plugins/bpipe-fd.sox ${cwd}/bin/plugins/bpipe-fd.so

check_two_logs
#
# ****FIXME**** test that all three files are restored correctly
#
diff ${cwd}/${file} ${cwd}/tmp/${file}
dstat=$?

# the test-plugin should create a RestoreObject, just check 
# compare restore object before/after
perl -ne '
 chomp();
 if (/Creating RestoreObject/) {
   @elt = split(/\s/, $_, 7);
   $clen = $elt[4];
   $cdata = $elt[6];
   $cname = $elt[5];
 } elsif (/Get RestoreObject/) {
   @elt = split(/\s/, $_, 8);
   $glen = $elt[4];
   $gdata = $elt[7];
   $gname = $elt[6];
 }
 END {
   $err=0;
   if ($clen ne $glen) {
     print "ERROR: $clen != $glen\n";
     $err++;
   }
   if ($cdata ne $gdata) {
     print "ERROR: <$cdata> != <$gdata>\n";
     $err++;
   }
   if ($cname ne $gname) {
     print "ERROR: $cname != $gname\n";
     $err++;
   }
   exit $err;
 }
' working/*.trace

estat=$?

end_test
